/**axios请求封装
 * 
 */
import axios from 'axios'
import Vue from 'vue';
import router from '@/router'
import { Toast } from 'vant';
Vue.use(Toast);


let toast = null;
const service = axios.create({
    baseURL: "https://yc211.cn:88/api/v1",  //url = baseURL + reques url 
    timeout: 5000, // 超时时间
    headers: { // 请求内容类型
        'Content-Type': "application/json"
    }
})

// 请求前拦截
service.interceptors.request.use(
    config => {
        console.log(config)
        //1、请求前动画
        toast = Toast.loading({
            duration: 0, // 持续展示 toast
            forbidClick: true,
            message: '努力搬砖中...'
        });
        //2、携带登录凭证
        if (config['isAuth']) {
            // 
            config.headers['token'] = JSON.parse(localStorage.getItem('token'))
        }
        // 登录状态

        return config
    }, err => {
        console.log(err)
        return Promise.reject(err)
    }
)
//响应后拦截
service.interceptors.response.use(
    response => {
        console.log(response.status)
        toast.clear()
        if (response.status === 200) {
            const res = response.data
            return res
        } else {
            return Promise.reject(response)
        }
    }, err => {
        toast.clear()
        if (err.response.status === 401) {
            localStorage.removeItem('token')
            router.push('/login')
        }
        return Promise.reject(err)
    }
)

export default service